package com.bluefish.bltuan.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.bluefish.bltuan.dao.ContentDao;
import com.bluefish.bltuan.module.cms.Content;
import com.bluefish.bltuan.module.cms.ContentType;

@Repository
public class ContentDaoImpl extends AbstractDaoImpl<Content, Integer>
	implements ContentDao{

	private static final String NICK = "nick";

	/**
	 * 
	 */
	private static final long serialVersionUID = 8912550396815078476L;
	
	private static final String UPDATE_CONTENT_AFTER_POSITION = "update com.bluefish.bltuan.module.cms.Content c" +
			" set c.position=c.position-1 where c.type=:type and c.position>";
	
	private static final String POSITION = "position";
	
	private static final String TYPE = "type";

	@SuppressWarnings("unchecked")
	public List<Content> listByType(final ContentType type) {
		return this.getHibernateTemplate().executeFind(new HibernateCallback<List<Content>>(){

			public List<Content> doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria criteria = session.createCriteria(Content.class);
				criteria.add(Restrictions.eq(TYPE, type));
				criteria.addOrder(Order.asc(POSITION));
				return criteria.list();
			}
		});
	}
	
	public int countByType(ContentType type) {
		return countByProperty(TYPE, type);
	}

	public void updatePositionAfter(final int pos, final ContentType type) {
		this.getHibernateTemplate().execute(new HibernateCallback<Object>(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(UPDATE_CONTENT_AFTER_POSITION+pos);
				query.setParameter(TYPE, type)
					.executeUpdate();
				return null;
			}
			
		});
	}
	
	public List<Content> listByNick(String nick) {
		return listByProperty(NICK, nick);
	}
}
